"""
题库管理模块 - 信号处理
"""
from django.db.models.signals import post_save, post_delete, pre_save
from django.dispatch import receiver
from django.db.models import Count, Sum

from .models import Question, QuestionBank, QuestionBankItem, QuestionTag, QuestionTagRelation, QuestionUsageHistory


@receiver(post_save, sender=Question)
def question_created(sender, instance, created, **kwargs):
    """题目创建后的信号处理"""
    if created:
        # 创建题目时，更新题目标签使用统计
        if instance.tags:
            for tag_name in instance.tags:
                tag, _ = QuestionTag.objects.get_or_create(
                    name=tag_name,
                    defaults={'category': 'auto_generated'}
                )
                tag.usage_count += 1
                tag.save(update_fields=['usage_count'])


@receiver(post_save, sender=QuestionBankItem)
def question_bank_item_created(sender, instance, created, **kwargs):
    """题库题目项创建后的信号处理"""
    if created:
        # 添加题目到题库后，更新题库统计信息
        instance.question_bank.update_statistics()


@receiver(post_delete, sender=QuestionBankItem)
def question_bank_item_deleted(sender, instance, **kwargs):
    """题库题目项删除后的信号处理"""
    # 从题库移除题目后，更新题库统计信息
    instance.question_bank.update_statistics()


@receiver(post_save, sender=QuestionUsageHistory)
def question_usage_recorded(sender, instance, created, **kwargs):
    """题目使用记录创建后的信号处理"""
    if created:
        # 记录题目使用情况
        instance.question.update_usage_statistics(instance.is_correct)


@receiver(post_save, sender=QuestionTagRelation)
def question_tag_relation_created(sender, instance, created, **kwargs):
    """题目标签关系创建后的信号处理"""
    if created:
        # 创建标签关系时，更新标签使用统计
        instance.tag.usage_count += 1
        instance.tag.save(update_fields=['usage_count'])


@receiver(post_delete, sender=QuestionTagRelation)
def question_tag_relation_deleted(sender, instance, **kwargs):
    """题目标签关系删除后的信号处理"""
    # 删除标签关系时，更新标签使用统计
    if instance.tag.usage_count > 0:
        instance.tag.usage_count -= 1
        instance.tag.save(update_fields=['usage_count'])


@receiver(pre_save, sender=Question)
def question_pre_save(sender, instance, **kwargs):
    """题目保存前的信号处理"""
    # 确保题目的正确率在有效范围内
    if instance.correct_rate is not None:
        instance.correct_rate = max(0.0, min(1.0, instance.correct_rate))

    # 确保分值为正数
    if instance.points is not None:
        instance.points = max(0, instance.points)

    # 确保时间限制为正数
    if instance.time_limit is not None:
        instance.time_limit = max(0, instance.time_limit)


@receiver(pre_save, sender=QuestionBank)
def question_bank_pre_save(sender, instance, **kwargs):
    """题库保存前的信号处理"""
    # 确保难度范围有效
    if isinstance(instance.difficulty_range, list) and len(instance.difficulty_range) == 2:
        min_diff, max_diff = instance.difficulty_range
        instance.difficulty_range = [
            max(1, min(5, min_diff)),
            max(1, min(5, max_diff))
        ]
        # 确保最小值不大于最大值
        if instance.difficulty_range[0] > instance.difficulty_range[1]:
            instance.difficulty_range = [instance.difficulty_range[1], instance.difficulty_range[0]]


@receiver([post_save, post_delete], sender=QuestionBankItem)
def update_question_bank_stats(sender, instance, **kwargs):
    """更新题库统计信息的通用信号处理"""
    try:
        instance.question_bank.update_statistics()
    except QuestionBank.DoesNotExist:
        # 题库可能已被删除，忽略此错误
        pass


@receiver(post_save, sender=Question)
def question_status_changed(sender, instance, created, **kwargs):
    """题目状态变更后的信号处理"""
    if not created:
        # 如果是更新操作，检查状态是否变更
        try:
            old_instance = sender.objects.get(pk=instance.pk)
            if old_instance.status != instance.status:
                # 状态变更，可能需要更新相关题库
                for bank_item in instance.bank_items.all():
                    if instance.status == 'active' and bank_item.status != 'active':
                        bank_item.status = 'active'
                        bank_item.save(update_fields=['status'])
                    elif instance.status != 'active' and bank_item.status == 'active':
                        bank_item.status = 'inactive'
                        bank_item.save(update_fields=['status'])
        except sender.DoesNotExist:
            pass